package com.example.module.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

public class HttpPostTask extends AsyncHttpTask {

	private static final String TAG = "HttpPostTask";

	public HttpPostTask(Context context) {
		super(context);
	}

	@Override
	public HttpTaskReponse doRequest(APIRequest request) throws Exception {
		HttpPost httpRequest = new HttpPost(request.getURL());
//		httpRequest.setHeader("Content-Type", "application/json");
//		httpRequest.setHeader("SessionKey", mSessionKey);
		
		if (request.getParams() != null) {
			List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			for (Entry<String, String> entry : request.getParams().entrySet()) {
				postParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			httpRequest.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
		}
			
		HttpResponse response = client.execute(httpRequest);
		
		HttpEntity resEntity = response.getEntity();
		String responseText = EntityUtils.toString(resEntity, HTTP.UTF_8);
		Log.d(TAG, "responseText=" + responseText);
		
		return new HttpTaskReponse(RESPONSE_OK, responseText);
	}

}
